<template>
  <div class="content">
    <div class="card_header">

    </div>

    <div class="card_list">
      <div class="card_header_button">
        <a-button type="primary" @click="editModal('add')">创建</a-button>
        <a-button type="primary" status="danger">删除</a-button>
      </div>
      <a-table :columns="columns" :data="data" :loading="loading">
        <template #avatar="{ record }">
          <a-avatar>
            <img :src="img + '/' + record.avatar" alt="">
          </a-avatar>
        </template>
        <template #auditStatus="{ record }">
          {{ record.auditStatus == 0 ? '待审核' : record.auditStatus == 1 ? '已通过' : '未通过' }}
        </template>
        <template #isHot="{ record }">
          {{ record.isHot == 0 ? '否' : '是' }}
        </template>
        <template #action="{ record }">
          <a-button type="text" @click="memberModal(record, 1)">成员</a-button>
          <a-button type="text" @click="editModal('edit', record)">编辑</a-button>
          <a-button type="text" @click="deleteModal(record.forumId)">删除</a-button>
        </template>
      </a-table>
    </div>

    <!-- 新增 or 编辑 贴吧 -->
    <a-modal :visible="editVi" :title="editTitle" @ok="editOk(editTitle)" @cancel="editNo" :width="700">
      <a-form :model="form" :label-col-props="{ span: 3, offset: 1 }">
        <a-form-item label="头像" name="avatar">
          <a-upload :action="url + '/upload/image'" @success="uploadSuccess" :show-file-list="false">
            <template #upload-button>
              <div v-if="!form.avatar"
                style="width: 100px;height: 100px;background-color: #eee;display: flex;align-items: center;justify-content: center;">
                请上传图片
              </div>
              <img v-else :src="img + '/' + form.avatar" style="width: 100px;height: 100px;object-fit: cover;" alt="">
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item label="吧主昵称" name="nickname">
          <div style="width: 100%;display: flex;justify-content: space-between;align-items: center;">
            {{ form.stickUser?.nickname || form.nickname }}
            <a-button type="primary" status="success" @click="memberModal(form, form.stickUser?.nickname ?
              null : 2)">{{ form.stickUser?.nickname ?
                '更换吧主' : '选择吧主' }}</a-button>
          </div>
        </a-form-item>
        <a-form-item label="贴吧名称" name="forumName">
          <a-input v-model="form.forumName" placeholder="请输入贴吧名称" />
        </a-form-item>
        <a-form-item label="贴吧类别" name="category">
          <a-select v-model="form.category">
            <a-option v-for="(res, index) in categoryList" :key="index" :value="res.name">{{ res.name }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="贴吧类目" name="postCategory">
          <div class="tag-wrap">
            <a-tag v-for="(item, index) in form.postCategory" :key="index" closable
              @close="() => { form.postCategory.splice(index, 1) }">{{ item }}</a-tag>
            <a-input style="width: 90px;" v-if="showInput" v-model="inputValue" ref="inputRef" size="mini"
              @keyup.enter="handAddCategory" @blur="handAddCategory"></a-input>

            <a-tag v-else :style="{
              backgroundColor: 'var(--color-fill-2)',
              cursor: 'pointer',
            }" @click="handEditCategory">
              <template #icon>
                <icon-plus-circle />添加类目
              </template>
            </a-tag>
          </div>
        </a-form-item>
        <a-form-item label="审核状态" name="auditStatus">
          <a-select v-model="form.auditStatus">
            <a-option value="0">待审核</a-option>
            <a-option value="1">已通过</a-option>
            <a-option value="2">未通过</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="简介">
          <a-textarea v-model="form.introduction">

          </a-textarea>
        </a-form-item>

      </a-form>
    </a-modal>

    <!-- 成员弹窗 -->
    <a-modal v-model:visible="detailVi" @ok="detailVi = false" :width="1100" title="成员列表">
      <a-table v-if="memberData != null" :columns="memberColumns" :data="memberData">
        <template #role="{ record }">
          {{ record.role == 1 ? '普通用户' : '管理员' }}
        </template>
        <template #avatar="{ record }">
          <a-avatar v-if="record.user?.avatar">
            <img :src="img + '/' + record.user?.avatar" alt="">
          </a-avatar>
          <a-avatar v-else>
            <icon-user />
          </a-avatar>
        </template>
        <template #gender="{ record }">
          {{ record.user?.gender == 1 ? '男' : '女' }}
        </template>
        <template #action="{ record }">
          <a-button type="text" @click="handManageMemeber(record)">转让</a-button>
        </template>
      </a-table>
    </a-modal>

    <!-- 用户弹窗 -->
    <a-modal v-model:visible="userVi" @ok="userVi = false" :width="1100" title="用户列表">
      <a-table :columns="userColumns" :data="userData">
        <template #avatar="{ record }">
          <a-avatar v-if="record.avatar">
            <img :src="img + '/' + record.avatar" alt="">
          </a-avatar>
          <a-avatar v-else>
            <icon-user />
          </a-avatar>
        </template>
        <template #gender="{ record }">
          {{ record.gender == 1 ? '男' : '女' }}
        </template>
        <template #action="{ record }">
          <a-button type="text" @click="handManageMemeber(record, 1)">选择</a-button>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { selectForum, insertForum, updateForum, deleteForum } from '@/api/forum';
import { selectMember, updateManage } from '@/api/member'
import { selectUser } from '@/api/user'
import { getCategoryList } from '@/api/category'
import { Message } from '@arco-design/web-vue'
import { Modal } from '@arco-design/web-vue'

// 主要表格表格配置
const columns = ref([
  { title: "贴吧ID", dataIndex: "forumId" },
  //   { title: "用户ID", dataIndex: "userId" },
  { title: "头像", dataIndex: "avatar", slotName: "avatar" },
  { title: "名称", dataIndex: "forumName" },
  { title: "浏览量", dataIndex: "viewCount" },
  { title: "评论量", dataIndex: "commentCount" },
  { title: "关注量", dataIndex: "followCount" },
  //   { title: "介绍", dataIndex: "introduction" },
  { title: "是否热门", dataIndex: "isHot", slotName: "isHot" },
  { title: "类别", dataIndex: "category" },
  //   { title: "帖子类别", dataIndex: "postCategory" },
  { title: "审核状态", dataIndex: "auditStatus", slotName: "auditStatus" },
  { title: "创建时间", dataIndex: "createTime" },
  //   { title: "修改时间", dataIndex: "updateTime" },
  { title: "操作", dataIndex: "action", slotName: "action" }
]);

// 获取数据
const img = import.meta.env.VITE_BASE_IMG
const url = import.meta.env.VITE_BASE_URL
const loading = ref(false);
const data = ref([]);
function selectForumApi() {
  loading.value = true;
  selectForum().then(res => {
    data.value = res.data;
    loading.value = false;
  });
}
// 获取类目列表
const categoryList = ref([])
function getCategoryListApi() {
  getCategoryList().then(res => {
    categoryList.value = res.data;
  })
}

// 文件上传
function uploadSuccess(res) {
  form.value.avatar = res.response.msg;
}

// 新增 or 编辑 弹窗
const form = ref({
  avatar: null,
  userId: null,
  nickname: null,
  forumName: null,
  category: null,
  postCategory: [],
  auditStatus: '0',
  introduction: null
})

const editVi = ref(false)
const editTitle = ref(null)
const showInput = ref(false)
const inputValue = ref('')
const inputRef = ref(null)

function handAddCategory() {
  if (showInput.value) {
    if (inputValue.value) {
      form.value.postCategory.push(inputValue.value)
      inputValue.value = ''
    }
  }
  showInput.value = false
}
function handEditCategory() {
  showInput.value = true
  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus();
    }
  })
}

function editModal(type, res) {
  if (type === 'add') {
    form.value = {
      avatar: null,
      userId: null,
      nickname: null,
      forumName: null,
      category: null,
      postCategory: [],
      auditStatus: '0',
      introduction: null
    }
    editTitle.value = '新增贴吧'
    memberData.value = null
  } else if (type === 'edit') {
    editTitle.value = '编辑贴吧'
    form.value = { ...JSON.parse(JSON.stringify(res)) };
    form.value.postCategory = JSON.parse(form.value.postCategory);
  }
  editVi.value = true;
}
// 弹窗逻辑 ok
async function editOk() {
  if (editTitle.value === '新增贴吧') {
    form.value.postCategory = JSON.stringify([...form.value.postCategory])
    let res = await insertForum(form.value);
    Message.success(res.msg);
  }
  if (editTitle.value === '编辑贴吧') {
    form.value.postCategory = JSON.stringify([...form.value.postCategory])
    let res = await updateForum(form.value);
    Message.success(res.msg)
  }
  selectForumApi();
  editVi.value = false;
}

// 弹窗逻辑 no
function editNo() {
  form.value = {};
  editVi.value = false;
}

// 成员弹窗逻辑
const detailVi = ref(false)
const memberData = ref(null)
const memberColumns = ref([
  { title: "用户昵称", dataIndex: "user.nickname" },
  { title: "用户头像", dataIndex: "user.avatar", slotName: "avatar" },
  { title: "身份", dataIndex: "role", slotName: "role" },
  { title: "性别", dataIndex: "user.gender", slotName: "gender" },
  { title: "地址", dataIndex: "user.address" },
  { title: "手机", dataIndex: "user.phone" },
  { title: "邮箱", dataIndex: "user.email" },
  { title: "出生日期", dataIndex: "user.birthDate" },
  { title: "操作", dataIndex: "action", slotName: "action" }

])
// 用户弹窗逻辑
const userVi = ref(false)
const userData = ref(null)
const userColumns = ref([
  { title: "用户昵称", dataIndex: "nickname" },
  { title: "用户头像", dataIndex: "avatar", slotName: "avatar" },
  { title: "性别", dataIndex: "gender", slotName: "gender" },
  { title: "地址", dataIndex: "address" },
  { title: "手机", dataIndex: "phone" },
  { title: "邮箱", dataIndex: "email" },
  { title: "出生日期", dataIndex: "birthDate" },
  { title: "操作", dataIndex: "action", slotName: "action" }
])

const memberId = ref(null)
async function memberModal(res, type = 0) {
  console.log(res);

  if (type === 2) {
    let { data } = await selectUser()
    userData.value = data
    userVi.value = true;
    return
  }
  if (res.userId != null) {
    memberId.value = res.forumId
    let { data } = await selectMember(res.forumId)
    memberData.value = data;
  }
  if (type === 1) {
    memberColumns.value = memberColumns.value.filter(res => res.dataIndex !== 'action');
  }
  else {
    if (!memberColumns.value.some(res => res.dataIndex == 'action')) {
      memberColumns.value.push({ title: "操作", dataIndex: "action", slotName: "action" })
    }
  }
  detailVi.value = true;
}

// 转让管理员
async function handManageMemeber(res, type) {
  if (type == 1) {
    form.value.userId = res.userId
    form.value.nickname = res.nickname
    Message.success('选择成功');
    userVi.value = false;
  } else {
    form.value.stickUser.nickname = res.user.nickname
    const updateResult = await updateManage(res.userId, res.forumId);
    Message.success(updateResult.msg);
    const memberResult = await selectMember(memberId.value);
    memberData.value = memberResult.data;
    form.value.userId = res.userId;
  }
  selectForumApi();
}

// 删除贴吧
async function deleteModal(forumId) {
  Modal.confirm({
    title: '确认删除',
    content: '确认删除该贴吧吗？',
    onOk: async () => {
      await deleteForum(forumId)
      Message.success('删除成功')
      selectForumApi();
    }
  })
}

onMounted(() => {
  selectForumApi();
  getCategoryListApi();
  const list = ref([{ id: '1', name: '2' }, { id: '2', name: '3' }])
  list.value = list.value.filter(item => item.id !== '1')
});

</script>

<style scoped>
.tag-wrap {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
</style>